<?php

header('Content-type: application/json');

if (isset($_REQUEST['id']) and is_numeric($_REQUEST['id'])) {
	$pages = $db->fetchAll("SELECT * FROM site_pages WHERE site_id=? AND parent_id=? ORDER BY sort", array($site['id'], $_REQUEST['id']));
	for($i=0;$i<count($pages);$i++) {
		list($pages[$i]['title'], $pages[$i]['latest_revision_id']) = array_values($db->fetchRow("SELECT title, id FROM site_pages_revisions WHERE page_id=? ORDER BY id DESC LIMIT 1", $pages[$i]['id']));
		$pages[$i]['children'] = $db->fetchOne("SELECT COUNT(*) FROM site_pages WHERE parent_id=?", $pages[$i]['id']);
	}
	$json = array();
	foreach ($pages as $page) {
		$class = '';
		if (!$page['active']) $class = 'inactive';
		if ($page['revision_id'] != $page['latest_revision_id']) $class .= ' unpublished';
		if ($page['children'] == 0) $class .= ' no-children';
		$json[] = array(
			'attributes' => array(
				'id'        => $page['id'], 
				'class'     => $class, 
				'rel'       => ($page['parent_id']==0 ? 'root' : 'page'), 
				'parent_id' => $page['parent_id']
			),
			'state' => 'closed',
			'data' => array('title' => $page['title'], 'icon' => "/admin/backend/resources/images/icons/folder.png")
		);
	}
}

echo json_encode($json);

